from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django_redis import get_redis_connection
import base64
import pickle

from .serializers import CartSerializer, CartSKUSerializer, CartDeleteSerializer, CartSelectAllSerializer
from .utils import merge_cart_cookie_to_redis
from goods.models import SKU


class CartView(APIView):
    """
    购物车
    在对购物车进行操作的时候，需要加权限认证，但是如果加permission_classes，会对所有请求操作购物车的用户进行权限认证
    这样未登录的用户就无法通过认真，无法对购物车进行操作，不符合业务需求，所以需要对perform_authentication方法进行重写，
    延迟对用户权限的认证
    """
    def perform_authentication(self, request):
        """重写此方法，延迟对用户权限的认证，在有需要认证的地方手动进行权限认证"""
        pass

    def post(self, request):
        """
        保存购物车信息
        两种情况：
            1. 用户登录情况，将购物车信息保存到redis数据库中
            2. 用户未登录情况，将购物车信息保存到cookie中
        :param request:
        :return:
        """
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 读取检验之后的参数
        sku_id = serializer.validated_data['sku_id']
        count = serializer.validated_data['count']
        selected = serializer.validated_data['selected']

        # 判断是否有用户登录
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            # 运行到此即为登录用户
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            # 给redis购物车进行增量存储或计算
            pl.hincrby('cart_%s' % user.id, sku_id, count)

            # 判断是否进行了勾选
            if selected:
                # 程序进行到此即为已勾选
                pl.sadd('selected_%s' % user.id, sku_id)

            pl.execute()  # 执行管道

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        else:
            # 运行到此即为未登录用户操作购物车
            """
            对为登录用户操作购物车信息存储到cookie中，首先我们先要获取cookie，查看cookie中是否已经有购物车信息
            如果已经有购物车信息，则对其进行增量修改、增加等操作
            如果没有则直接添加信息
            """
            # 获取cookie中的购物车信息
            cart_str = request.COOKIES.get('cart')  # 字符串

            if cart_str:
                # 将字符串转换为bytes形式字符串
                cart_str_bytes = cart_str.encode()
                # 将bytes字符串转换为bytes字典类型
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 将bytes字典转换为普通字典
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                # 如果cookie中没有购物车信息，就创建一个空字典，方便后续的数据构造
                cart_dict = {}

            # 添加数据到字典中，构造响应数据
            if sku_id in cart_dict:
                # 程序执行到此，证明此商品已经在购物车中，将对count进行修改即可
                origin_count = cart_dict[sku_id]['count']
                count += origin_count

            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            # 将普通字典转换成bytes字典
            cookie_cart_dict_bytes = pickle.dumps(cart_dict)
            # 将bytes字典转换成bytes字符串
            cookie_cart_str_bytes = base64.b64encode(cookie_cart_dict_bytes)
            # 将bytes字符串转换成字符串
            cookie_cart_str = cookie_cart_str_bytes.decode()

            # 设置cookie
            response = Response(serializer.data, status=status.HTTP_201_CREATED)
            response.set_cookie('cart', cookie_cart_str)

            return response

    def get(self, request):
        """
        读取购物车信息
        :param request:
        :return:
        """
        # 判断是否有用户登录
        try:
            user = request.user
        except Exception:
            user = None

        response = Response()

        if user is not None and user.is_authenticated:
            # 用户登录

            response = merge_cart_cookie_to_redis(request, user, response)

            redis_conn = get_redis_connection('cart')
            # 查询redis中购物车数据
            # redis_cart_dict = {b'sku_id_1': b'count_1', b'sku_id_2': b'count_2'}
            redis_cart_dict = redis_conn.hgetall('cart_%s' % user.id)
            # 查询是否被勾选
            # redis_selected = [b'sku_id_1']
            redis_selected = redis_conn.smembers('selected_%s' % user.id)
            """
            构造数据格式
            {
                sku_id10: {
                    "count": 10,  // 数量
                    "selected": True  // 是否勾选
                },
                sku_id20: {
                    "count": 20,
                    "selected": False
                },
                ...
            }
            """
            # 定义一个空字典
            cart_dict = {}
            for sku_id, count in redis_cart_dict.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in redis_selected  # 如果sku_id在redis_selected中，返回True;反之，返回False
                }

        else:
            # 用户未登录，操作cookie购物车数据
            # 获取cookie中的购物车信息
            cart_str = request.COOKIES.get('cart')  # 字符串

            if cart_str:
                # 将字符串转换为bytes形式字符串
                cart_str_bytes = cart_str.encode()
                # 将bytes字符串转换为bytes字典类型
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 将bytes字典转换为普通字典
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                # 如果cookie中没有购物车信息，就创建一个空字典，方便后续的数据构造
                cart_dict = {}

        # 根据sku_id查询出所有购物车中的商品
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)

        # 因为SKU中没有count和selected属性，所以手动为每一个SKU添加这两个属性
        for sku in skus:
            sku.count = cart_dict[sku.id]['count']
            sku.selected =cart_dict[sku.id]['selected']

        serializer = CartSKUSerializer(skus, many=True)
        response.data = serializer.data
        # response = Response(serializer.data)
        # if user:
        #     response = merge_cart_cookie_to_redis(request, user, response)

        return response

    def put(self, request):
        """
        更新购物车信息
        :param request:
        :return:
        """
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 读取检验之后的参数
        sku_id = serializer.validated_data['sku_id']
        count = serializer.validated_data['count']
        selected = serializer.validated_data['selected']

        # 判断是否有用户登录
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            # 运行到此即为登录用户
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            # 更新购物车商品数量
            pl.hset('cart_%s' % user.id, sku_id, count)

            # 判断是否进行了勾选
            if selected:
                # 程序进行到此即为已勾选
                pl.sadd('selected_%s' % user.id, sku_id)
            else:
                pl.srem('selected_%s' % user.id, sku_id)

            pl.execute()  # 执行管道

            return Response(serializer.data)

        else:
            # 运行到此即为未登录用户操作购物车
            """
            对为登录用户操作购物车信息存储到cookie中，首先我们先要获取cookie，查看cookie中是否已经有购物车信息
            如果已经有购物车信息，则对其进行增量修改、增加等操作
            如果没有则直接添加信息
            """
            # 获取cookie中的购物车信息
            cart_str = request.COOKIES.get('cart')  # 字符串

            if cart_str:
                # 将字符串转换为bytes形式字符串
                cart_str_bytes = cart_str.encode()
                # 将bytes字符串转换为bytes字典类型
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 将bytes字典转换为普通字典
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                # 如果cookie中没有购物车信息，就创建一个空字典，方便后续的数据构造
                cart_dict = {}

            # 添加数据到字典中，构造响应数据
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            # 将普通字典转换成bytes字典
            cookie_cart_dict_bytes = pickle.dumps(cart_dict)
            # 将bytes字典转换成bytes字符串
            cookie_cart_str_bytes = base64.b64encode(cookie_cart_dict_bytes)
            # 将bytes字符串转换成字符串
            cookie_cart_str = cookie_cart_str_bytes.decode()

            # 设置cookie
            response = Response(serializer.data)
            response.set_cookie('cart', cookie_cart_str)

            return response

    def delete(self, request):
        """
        删除购物车信息
        :param request:
        :return:
        """
        serializer = CartDeleteSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data['sku_id']

        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            pl.hdel('cart_%s' % user.id, sku_id)
            pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()

            return Response(status=status.HTTP_204_NO_CONTENT)

        else:
            cart_str = request.COOKIES.get('cart')

            response = Response(status=status.HTTP_204_NO_CONTENT)

            if cart_str:
                # 将字符串转换为bytes形式字符串
                cart_str_bytes = cart_str.encode()
                # 将bytes字符串转换为bytes字典类型
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 将bytes字典转换为普通字典
                cart_dict = pickle.loads(cart_dict_bytes)

                if sku_id in cart_dict:
                    del cart_dict[sku_id]

                    # 将普通字典转换成bytes字典
                    cookie_cart_dict_bytes = pickle.dumps(cart_dict)
                    # 将bytes字典转换成bytes字符串
                    cookie_cart_str_bytes = base64.b64encode(cookie_cart_dict_bytes)
                    # 将bytes字符串转换成字符串
                    cookie_cart_str = cookie_cart_str_bytes.decode()

                    # 设置cookie
                    response.set_cookie('cart', cookie_cart_str)

                return response


class CartSelectAllView(APIView):
    """购物车全选或取消全选"""

    def perform_authentication(self, request):
        """重写此方法，延迟对用户权限的认证，在有需要认证的地方手动进行权限认证"""
        pass

    def put(self, request):
        """
        传入selected参数，如果是true全选，用户未登录操作cookie数据，将每个SKU的selected属性都置为true，登录用户将redis中购物车的所有SKU的id添加到selected中
        如果是false，用户未登录操作cookie数据，将每个SKU的selected属性都置为false，登录用户将redis中购物车的selected中的所有SKU的id全部删除
        :param request:
        :return:
        """
        serializer = CartSelectAllSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        selected = serializer.validated_data['selected']

        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            redis_cart_dict = redis_conn.hgetall('cart_%s' % user.id)
            sku_ids = redis_cart_dict.keys()

            if selected:
                pl.sadd('selected_%s' % user.id, *sku_ids)
            else:
                pl.srem('selected_%s' % user.id, *sku_ids)

            pl.execute()

            return Response({'message': 'OK'})

        else:
            cart_str = request.COOKIES.get('cart')
            response = Response({'message': 'OK'})
            if cart_str:
                # 将字符串转换为bytes形式字符串
                cart_str_bytes = cart_str.encode()
                # 将bytes字符串转换为bytes字典类型
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 将bytes字典转换为普通字典
                cart_dict = pickle.loads(cart_dict_bytes)

                # if selected:
                #     for sku_id in cart_dict:
                #         cart_dict[sku_id]['selected'] = True
                # else:
                #     for sku_id in cart_dict:
                #         cart_dict[sku_id]['selected'] = False
                for sku_id in cart_dict:
                    cart_dict[sku_id]['selected'] = selected

                # 将普通字典转换成bytes字典
                cookie_cart_dict_bytes = pickle.dumps(cart_dict)
                # 将bytes字典转换成bytes字符串
                cookie_cart_str_bytes = base64.b64encode(cookie_cart_dict_bytes)
                # 将bytes字符串转换成字符串
                cookie_cart_str = cookie_cart_str_bytes.decode()

                # 设置cookie
                response.set_cookie('cart', cookie_cart_str)

            return response






